<template>
	<view class="left-search">
		<view class="flex items-center justify-between top p-10px">
			<view style="color: #666666">{{ props.name }}选择</view>
			<view class="flex items-center">
				<view class="flex items-center">
					<template v-for="(btn, index) in buttons" :key="index">
						<dx-icon size="18" v-if="btn === 'refresh'" name="refresh" @click="getList()"></dx-icon>
						<dx-icon
							class="ml-8px"
							v-else-if="btn === 'add'"
							v-permission="`${funcName}/${urls.add}`"
							name="plus"
							@click="formGroup('add')"
						></dx-icon>
						<dx-icon class="ml-8px" v-else :name="btn" @click="toolClick(btn)"></dx-icon>
					</template>
				</view>
			</view>
		</view>
		<view class="content text-center">
			<el-scrollbar v-loading="loading">
				<el-radio-group v-model="value" @change="change">
					<view
						class="px-15px mt-12px"
						ref="buttonRefs"
						style="width: 100%"
						v-for="(item, index) in list"
						:key="item._id"
						@contextmenu.prevent="onContextmenu(item, $event)"
					>
						<el-radio style="width: 100%" :value="index" :label="item[props.field]" border></el-radio>
					</view>
				</el-radio-group>
			</el-scrollbar>
		</view>
		<!-- 右键菜单 -->
		<dx-context-menu ref="contextMenuRef" @menuClick="menuClick"></dx-context-menu>
	</view>
</template>
<script setup lang="ts" name="DxLeftSearch">
import { onMounted, ref } from 'vue';
import { axios } from '@/uni_modules/dx-admin/api/index';
const props = withDefaults(
	defineProps<{
		funcName?: string;
		name?: string;
		urls: any;
		buttons?: any;
		field?: string;
		defaultRow?: object;
		defaultId?: string;
	}>(),
	{
		funcName: 'dx-func-admin',
		name: '分组',
		field: 'name',
		buttons: ['refresh', 'add'],
		defaultRow: () => ({
			name: '未分组',
			_id: '',
		}),
		defaultId: '',
	}
);
const value = ref(0);
const loading = ref(false);
// 绑定关系
const $emit = defineEmits(['change', 'toolClick']);
function change(val: any) {
	$emit('change', { ...list.value[val] });
}
function toolClick(value: any) {
	$emit('toolClick', value);
}
// 列表获取
const list = ref<any[]>([]);
const getList = function () {
	loading.value = true;
	axios
		.send(props.urls?.index, props.funcName)
		.then((res) => {
			let groupList: any = [props.defaultRow];
			if (Array.isArray(res.data) && res.data.length) {
				groupList = [...groupList, ...res.data];
			} else if (res.data?.list && res.data.list?.length) {
				groupList = [...groupList, ...res.data.list];
			}
			let index = groupList.findIndex((item: any) => item._id === props.defaultId);
			if (index !== -1) {
				value.value = index;
			}
			list.value = groupList;
		})
		.finally(() => {
			loading.value = false;
		});
};
onMounted(() => {
	getList();
});
const row = {
	_id: '',
	[props.field]: '',
};
/**
 * 添加分组
 * @param {*} type
 */
function formGroup(type = 'add') {
	if (type === 'add') {
		row._id = '';
		row[props.field] = '';
	}
	ElMessageBox.prompt('', `${type === 'add' ? '添加' : '编辑'}${props.name}`, {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputValue: row[props.field],
		inputPlaceholder: `请输入${props.name}名称`,
		inputValidator: function (value) {
			if (!value) {
				return `${props.name}名称不能为空`;
			}
			return true;
		},
	})
		.then(({ value }) => {
			let data = { [props.field]: value };
			if (type === 'edit') {
				data._id = row._id;
			}
			axios.send(type === 'add' ? props.urls?.add : props.urls?.edit, props.funcName, data).then((res) => {
				if (res.code === 1000) {
					ElMessage.success('操作成功');
					getList();
				} else {
					ElMessage.error(res.message);
				}
			});
		})
		.catch(() => {});
}
// 右键菜单
const contextMenuRef = ref();
function onContextmenu(item: any, event: any) {
	if(!item._id) return;
	row._id = item._id;
	row[props.field] = item[props.field];
	contextMenuRef.value?.open(
		[
			{
				name: 'edit',
				label: '编辑',
				icon: 'edit',
			},
			{
				name: 'del',
				label: '删除',
				icon: 'delete',
			},
		],
		{ x: event.clientX, y: event.clientY }
	);
}
function menuClick(item: any) {
	if (item.name === 'edit') {
		formGroup('edit');
	} else if (item.name === 'del') {
		delGroup();
	}
}
function delGroup() {
	ElMessageBox.confirm(`确定删除${props.name}吗?`, '温馨提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'error',
	})
		.then(() => {
			axios.send(props.urls?.del, props.funcName, { ids: row._id }).then((res) => {
				if (res.code === 1000) {
					ElMessage.success('删除成功');
					getList();
				} else {
					ElMessage.error(res.message);
				}
			});
		})
		.catch(() => {});
}
</script>
<style lang="scss" scoped>
.left-search {
	height: 100%;
	width: 100%;
	.top {
		border-bottom: 1px solid #ebeef5;
	}
	.content {
		height: calc(100% - 60px);
	}
}
::v-deep{
	.el-radio-group{
		width: 100%;
	}
}
</style>
